package com.swgk.core.util;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @author : younghow
 * @date : 2021/9/15 11:57
 * description: 类数据判空转换工具
 */
public class TransObjectUtils {

    public static Object transObject(Object entity) throws IllegalAccessException {
        if (entity == null) {
            throw new RuntimeException("entity这个对象是空的");
        }

        Class<?> clazz = entity.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(entity);
            if (value == null) {
                if ("byte".equals(field.getType().getName())) {
                    field.set(entity, 0);
                }

                if ("short".equals(field.getType().getName())) {
                    field.set(entity, 0);
                }

                if ("int".equals(field.getType().getName())) {
                    field.set(entity, 0);
                }

                if ("long".equals(field.getType().getName())) {
                    field.set(entity, 0);
                }

                if ("float".equals(field.getType().getName())) {
                    field.set(entity, 0f);
                }

                if ("double".equals(field.getType().getName())) {
                    field.set(entity, 0.0);
                }

                if ("char".equals(field.getType().getName())) {
                    field.set(entity, ' ');
                }

                if ("java.util.List".equals(field.getType().getName())) {
                    field.set(entity, new ArrayList<>());
                }

                if ("java.lang.String".equals(field.getType().getName())) {
                    field.set(entity, "");
                }

                if ("java.lang.Object".equals(field.getType().getName())) {
                    field.set(entity, new Object());
                }
            }
        }

        return entity;
    }
}
